package com.cndongtai.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import com.cndongtai.net.analysis.MessageFilter;

public class SocketContainer extends Thread{

	private String panId;
	private Socket socket;
	private boolean stopFlag=false;
	
	public SocketContainer(String panId, Socket socket) {
		this.panId = panId;
		this.socket = socket;
	}
	
	public void stopThread() {
		this.stopFlag = true;
	}
	
	public void closeSocket() {
		try {
			if(socket!=null) {
				socket.close();
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		
		NetController.getSocketPool().remove(panId);
	}
	
	public boolean send(byte[] msg) {
		try {
			OutputStream out = socket.getOutputStream();
			out.write(msg);
			out.flush();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			stopThread();
			closeSocket();
		}
		
		return false;
	}
	
	public void run() {
		try {
			while(!stopFlag) {
				InputStream in = socket.getInputStream();
				byte[] buf = new byte[10240];
				
				int length = in.read(buf);
				System.out.println("接收到报文了,长度>" + length);
				if(length>10) {
					// 进行报文拆分
					//for()
					byte[] msg = new byte[length];
					System.arraycopy(buf, 0, msg, 0, length);
					
					MessageFilter filter = new MessageFilter();
					filter.doMsg(msg);
				}else {
					// 如果超过15分钟未接收到心跳，视为掉线，服务器主动断开连接
					long time = NetController.onlineMap.get(panId);
					if(System.currentTimeMillis()-time>1000*60*3) {
						socket.close();
						stopFlag = true;
					}
					
					try {
						Thread.sleep(500);
					} catch (InterruptedException e1) {
						e1.printStackTrace();
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
